package com.fivestar.pmanager.web.filter;

import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.fivestar.pmanager.core.util.CodeHelper.isNotNullOrEmpty;

/**
 * 初始化日志MDC
 *
 */
public class LoggerFilter implements Filter
{

    @Override
    public void destroy()
    {

    }


    @Override
    public void doFilter(ServletRequest paramServletRequest,
            ServletResponse paramServletResponse, FilterChain paramFilterChain)
            throws IOException, ServletException
    {
        try
        {
            if (paramServletRequest instanceof HttpServletRequest)
            {
                String loginId = getLoginId((HttpServletRequest) paramServletRequest);
                MDC.put("user",loginId);
            }
            paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
        }
        finally
        {
            MDC.remove("user"); 
        }
    }

    @Override
    public void init(FilterConfig paramFilterConfig) throws ServletException
    {

    }

    private String getLoginId(HttpServletRequest request)
    {
        String loginId = request.getSession().getId();

        return isNotNullOrEmpty(loginId) ? loginId : "unknow";
    }


}
